const fs = require('fs');
const path = require('path');

class JsonStringifyPlugin {
  constructor(options) {
    this.options = {
      inputDir: path.resolve(__dirname, '../public'), // 输入目录，默认为 ../static
      ...options
    };
  }

  apply(compiler) {
    compiler.hooks.beforeRun.tapAsync('JsonStringifyPlugin', (compilation, callback) => {
      const { inputDir,  } = this.options;
      this.processDirectory(inputDir);
      callback();
    });
  }

  processDirectory(inputDir,) {
    fs.readdirSync(inputDir).forEach(file => {
      const filePath = path.join(inputDir, file);
      if (fs.lstatSync(filePath).isDirectory()) {
        this.processDirectory(filePath);
      } else if (file.endsWith('.json')) {
        // 处理 JSON 文件
        const content = fs.readFileSync(filePath, 'utf8');
        try {
          const parsed = JSON.parse(content);
          const stringified = JSON.stringify(parsed, null, 0); // 使用 JSON.stringify 压缩
          fs.writeFileSync(filePath, stringified, 'utf8');
          console.log(`Processed JSON file: ${filePath}`);
        } catch (error) {
          console.error(`Error processing JSON file ${filePath}:`, error);
        }
      }
    });
  }
}

module.exports = JsonStringifyPlugin;